package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.InventoryCriteria;
import com.leo.ibatis.demo.dao.InventoryDao;
import com.leo.ibatis.demo.domain.Inventory;
import com.leo.ibatis.demo.util.Paging;

public class InventoryDaoImpl extends SqlMapClientDaoSupport implements InventoryDao {

	public void insert(Inventory inventory) throws DataAccessException {
		getSqlMapClientTemplate().insert("Inventory.insert", inventory);
	}

	public int update(Inventory inventory) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Inventory.update", inventory, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String itemid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Inventory.delete", itemid, actualRowsAffected);

		return actualRowsAffected;
	}

	public Inventory select(String itemid) throws DataAccessException {
		return (Inventory) getSqlMapClientTemplate().queryForObject("Inventory.select", itemid);
	}

	@SuppressWarnings("unchecked")
	public List<Inventory> list(InventoryCriteria inventoryCriteria) throws DataAccessException {
		Assert.notNull(inventoryCriteria, "inventoryCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Inventory.list", inventoryCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Inventory> listOnPage(InventoryCriteria inventoryCriteria) throws DataAccessException {
		Assert.notNull(inventoryCriteria, "inventoryCriteria must not be null");
		Assert.notNull(inventoryCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(inventoryCriteria);
		Paging paging = inventoryCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Inventory.list", inventoryCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(InventoryCriteria inventoryCriteria) throws DataAccessException {
		Assert.notNull(inventoryCriteria, "inventoryCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Inventory.count", inventoryCriteria)).intValue();
	}

}
